package controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
@Controller(value="clientWebSocketHandler")
@RequestMapping("/ws/client")
public class ClientWebSocketHandler extends TextWebSocketHandler{
    private List<WebSocketSession> sessionList =new ArrayList<WebSocketSession>();

    public List<WebSocketSession> getSessionList() {
        return sessionList;
    }

    public void setSessionList(List<WebSocketSession> sessionList) {
        this.sessionList = sessionList;
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        for(WebSocketSession sen: sessionList){
            try {
                sen.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session)
            throws Exception {
        sessionList.add(session);
    }

    @Override
    public void handleTransportError(WebSocketSession session,
                                     Throwable exception) throws Exception {
        // 消息传输出错时调用
        System.out.println("handleTransportError");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session,
                                      CloseStatus closeStatus) throws Exception {
        sessionList.remove(session);
    }
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    public void notifyCustomer(String message){
        TextMessage msg = new TextMessage(message);
        for (WebSocketSession session : sessionList) {
            try {
                session.sendMessage(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}